/*******************************************************************************
 * Copyright 2011 Mile Orešković
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.mileoresko.hsm;

import java.util.HashSet;
import java.util.Iterator;

public abstract class HSMBareState {

    protected String label;
    protected HierarchicalStateMachine owningStateMachine;

    private HashSet nestedHsms;

    protected HSMBareState(final HierarchicalStateMachine owningStateMachine, final String label) {
        this.label = label;
        this.owningStateMachine = owningStateMachine;
        if (owningStateMachine != null) {
            owningStateMachine.smLog("Creating state " + label);
        }
        defineNestedHsms();
    }

    protected final void addNestedHsm(final HierarchicalStateMachine hsm) {
        if (nestedHsms == null) {
            nestedHsms = new HashSet();
        }
        nestedHsms.add(hsm);
    }

    protected abstract void defineNestedHsms();

    protected abstract void entryAction(final Object arg);

    protected abstract void exitAction(final Object arg);
    
    protected abstract boolean isTerminal();

    final void dispatchEvent(final HSMEvent event, final Object arg) {
        if (nestedHsms == null) {
            owningStateMachine.smLog("No nested HSMs in state " + label);
            return;
        }
        final Iterator itr = nestedHsms.iterator();
        while (itr.hasNext()) {
            ((HierarchicalStateMachine) itr.next()).pushEvent(event, arg);
        }
    }

    final void entryActionInternal(final Object arg) {
        owningStateMachine.smLog("Entering state: " + label);
        entryAction(arg);
        if (nestedHsms != null) {
            final Iterator itr = nestedHsms.iterator();
            while (itr.hasNext()) {
                ((HierarchicalStateMachine) itr.next()).start(arg);
            }
        }
    }

    final void exitActionInternal(final Object arg) {
        owningStateMachine.smLog("Exiting state: " + label);
        if (nestedHsms != null) {
            final Iterator itr = nestedHsms.iterator();
            while (itr.hasNext()) {
                ((HierarchicalStateMachine) itr.next()).halt(arg);
            }
        }
        exitAction(arg);
    }

    public String toString() {
        return label;
    }
}
